<?php
/**
 * 登录控制器
 */

namespace App\Http\Controllers\Backend;

use Carbon\Carbon;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use App\Libs\RedisLib;
use \App\Model\BackendUserModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;

class LoginController extends Controller
{
    /**
     * 登录页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login()
    {
        $this->data['title'] = '登录';
        return view('backend.login.login', $this->data);
    }

    /**
     * 注册页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function register()
    {
        $this->data['title'] = '注册';
        return view('backend.login.register', $this->data);
    }

    /**
     * 忘记密码页面渲染
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function forget()
    {
        $this->data['title'] = '忘记密码';
        return view('backend.login.forget', $this->data);
    }

    // 注册账号
    public function registerPost()
    {
        $emailCodeKey = RedisLib::getEmailRedisKey(3, self::$params['email']);
        $emailCode = Redis::get($emailCodeKey);
        if ($emailCode != self::$params['email_code']) {
            return $this->responseError('邮箱验证码错误');
        }

        self::$params['scene_type'] = 1;
        self::$params['info'] = self::$params['clicaptcha_code'];
        $cliCaptchaController = app()->make('App\Http\Controllers\Backend\CliCaptchaController');
        $checkRes = app()->call([$cliCaptchaController, 'check']);
        if ($checkRes != 1) {
            return $this->responseError('图形验证码错误');
        }

        if (BackendUserModel::where(['email' => self::$params['email']])->get()->toArray()) {
            return $this->responseError('此邮箱已经注册');
        }

        $data = [
            'nickname' => '新用户',
            'headimgurl' => 'http://laravel.lincanming.xyz/static/images/default/default_headimgurl.png',
            'email' => self::$params['email'],
            'password' => app('security_lib')->passwordEncrypt(self::$params['password']),
            'create_time' => time()
        ];
        if (BackendUserModel::insert($data)) {
            return $this->responseSuccess();
        } else {
            return $this->responseError();
        }
    }

    // 登录
    public function loginPost()
    {
        $backendUser = BackendUserModel::where(['email' => self::$params['email']])->first();
        if (empty($backendUser)) {
            return $this->responseError('邮箱不存在');
        }

        if (app('security_lib')->verifyPassword(self::$params['password'], $backendUser['password']) !== true) {
            return $this->responseError('密码不正确');
        }

        Auth::login($backendUser, true);// 自定义登录
        // 登录状态默认是5年，不改变源码下，改为120分钟; 优化,放在事件中
        $rememberTokenExpireMinutes = 180;
        $rememberTokenName = Auth::getRecallerName();
        Cookie::queue($rememberTokenName, Cookie::get($rememberTokenName), $rememberTokenExpireMinutes);
        return $this->responseSuccess('登录成功');
    }

    // 注册账号
    public function forgetPost()
    {
        $emailCodeKey = RedisLib::getEmailRedisKey(4, self::$params['email']);
        $emailCode = Redis::get($emailCodeKey);
        if ($emailCode != self::$params['email_code']) {
            return $this->responseError('邮箱验证码错误');
        }

        self::$params['scene_type'] = 2;
        self::$params['info'] = self::$params['clicaptcha_code'];
        $cliCaptchaController = app()->make('App\Http\Controllers\Backend\CliCaptchaController');
        $checkRes = app()->call([$cliCaptchaController, 'check']);
        if ($checkRes != 1) {
            return $this->responseError('图形验证码错误');
        }

        $backendUser = BackendUserModel::where(['email' => self::$params['email']])->first();
        if (empty($backendUser)) {
            return $this->responseError('此邮箱沒有注册');
        }

        if (BackendUserModel::where(['id' => $backendUser->id])->update(['password' => app('security_lib')->passwordEncrypt(self::$params['password'])])) {
            return $this->responseSuccess();
        } else {
            return $this->responseError();
        }
    }

    /**
     * 发送邮箱验证码
     * @return false|string
     */
    public function postEmail()
    {
        $scene_body = [
            // 注册场景
            1 => [
                'emailBody' => '<h1>您的注册验证码是: <strong>',
                'subject' => '注册账号-邮箱验证码',
                'receiveUser' => '注册用户',
                'keyMethod' => 'getRegisterEmailKey',
                'limit' => RedisLib::$register_email_limit,
            ],
            // 忘记密码场景
            2 => [
                'emailBody' => '<h1>您的找回验证码是: <strong>',
                'subject' => '忘记密码-密码找回',
                'receiveUser' => '忘记密码用户',
                'keyMethod' => 'getForgetEmailKey',
                'limit' => RedisLib::$forget_email_limit,
            ],
        ];

        $sceneData = $scene_body[self::$params['scene_type']];
        $expire = Carbon::tomorrow()->timestamp - time();
        $redisKey = RedisLib::getEmailRedisKey(self::$params['scene_type'], self::$params['email']);
        $alreadySendTimes = Redis::get($redisKey) ? : 0;
        if ($alreadySendTimes > $sceneData['limit']) {
            return $this->responseError('邮件发送次数已经达到上限');
        }

        $emailCode = sprintf('%06d', mt_rand(0, 999999));
        $emailCodeKey = RedisLib::getEmailRedisKey(self::$params['scene_type'] + 2, self::$params['email']);
        $username = config()->get('lcm.admin_email_account');
        $password = config()->get('lcm.admin_email_password');
        $swiftSmtptransportObj = new \Swift_SmtpTransport('smtp.163.com', 465, 'ssl');
        $transport = $swiftSmtptransportObj->setUsername($username)->setPassword($password);
        $mailer = new \Swift_Mailer($transport);
        $message = new \Swift_Message();
        // 设置邮件主题
        $sceneData['emailBody'] .= $emailCode . ' </strong>; 请在5分钟内输入';
        $message->setSubject($sceneData['subject'])->setBody($sceneData['emailBody'], 'text/html');

//        // 创建attachment对象，content-type这个参数可以省略
//        $attachment = \Swift_Attachment::fromPath('image.jpg', 'image/jpeg')->setFilename('cool.jpg');
//        // 添加附件
//        $message->attach($attachment); // 一个一个的加上去

        // 用关联数组设置收件人地址，可以设置多个收件人
        $message->setTo(array(self::$params['email'] => $sceneData['receiveUser']));
        // 用关联数组设置发件人地址，可以设置多个发件人
        $message->setFrom(array($username => 'lcm'));

//        // 添加抄送人
//        $message->setCc(array(
//            'Cc@qq.com' => 'Cc'
//        ));
//
//        // 添加密送人
//        $message->setBcc(array(
//            'Bcc@qq.com' => 'Bcc'
//        ));

        // 设置邮件回执
//        $message->setReadReceiptTo('receipt@163.com');

        // 发送邮件
        if ($mailer->send($message) == 1) {
            Redis::setex($redisKey, $expire, ++$alreadySendTimes);
            Redis::setex($emailCodeKey, 300, $emailCode);
            return $this->responseSuccess();
        } else {
            return $this->responseError();
        }
    }

    /** 登出 */
    public function logoutPost()
    {
        Auth::logout();
        return redirect('/');
    }
}
